package site.shihuan.helpdesk.im.core;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import site.shihuan.helpdesk.im.message.BaseMessage;
import site.shihuan.helpdesk.im.message.IMessage;
import site.shihuan.helpdesk.im.message.impl.ContactMessage;
import site.shihuan.helpdesk.im.exception.DecodeException;
import site.shihuan.helpdesk.im.message.impl.ChatMessage;
import site.shihuan.helpdesk.im.message.impl.RtcMessage;

/**
 * 编码
 *
 * @author 周世焕
 * @Date 2021/2/2 21:08
 */
@Slf4j
public class MessageDecoder {

    public static BaseMessage decode(String data) throws DecodeException{
        log.debug("接收数据: {}" ,data);
        BaseMessage message;
        JSONObject jsonObject = JSONUtil.parseObj(data);
        short messageType = jsonObject.getShort(IMessage.PROPERTY_TYPE,(short) -1);
        switch (messageType) {
            case IMessage.TYPE_CHAT:
                message = new ChatMessage();
                break;
            case IMessage.TYPE_CONTACT:
                message = new ContactMessage();
                break;
            case IMessage.TYPE_RTC_CONNECT:
                message = new RtcMessage();
                break;
            default:
                throw new DecodeException("控制报文类型错误：" + messageType);
        }
        message.decode(jsonObject.getStr(IMessage.PROPERTY_CONTENT));
        return message;
    }

}
